package com.cxx.purchasecharge.component.controller;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.CustomerStatusBean;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.CustomerStatus;
import com.cxx.purchasecharge.dal.CustomerStatusDao;

@Controller
@RequestMapping ("/customerStatus")
public class CustomerStatusManager
{
    private static final Logger logger = Logger.getLogger (CustomerStatusManager.class);

    @Autowired
    private CustomerStatusDao customerStatusDao;

    @RequestMapping (value = "/")
    public String redirectToCustomerStatusManagement (ModelMap model)
    {
        return "customerStatusManagement";
    }

    @RequestMapping (value = "/checkExist", method = RequestMethod.POST)
    public @ResponseBody
    String checkExist (@RequestParam String customerStatusId, @RequestParam String name)
    {
        if (StringUtils.isBlank (customerStatusId))
        {
            // new
            CustomerStatus obj = customerStatusDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long id = Long.parseLong (customerStatusId);
            CustomerStatus customerStatus = customerStatusDao.findByName (name);
            if (null != customerStatus && customerStatus.getId () != id)
            {
                return "false";
            }
        }

        return "true";
    }

    @RequestMapping (value = "/getAllStatus", method = RequestMethod.POST)
    public @ResponseBody
    String getCustomerStatuss (DataGridRequestForm dataGridRequestForm)
    {
        List <CustomerStatus> units = (List <CustomerStatus>) customerStatusDao.findAll ();

        JSONArray jsonObject = JSONArray.fromObject (units);
        return jsonObject.toString ();
    }

    @RequestMapping (value = "/newCustomerStatus", method = RequestMethod.POST)
    public @ResponseBody
    String addCustomerStatus (CustomerStatusBean unitBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            CustomerStatus unit = new CustomerStatus (unitBean.getName ());
            String unitId = unitBean.getId ();
            if (null != unitId && !"".equals (unitId))
            {
                unit.setId (Long.parseLong (unitId));
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                customerStatusDao.save (unit);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_CUSTOMER_STATUS))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_CUSTOMER_STATUS))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/updateCustomerStatus", method = RequestMethod.POST)
    public @ResponseBody
    String updateCustomerStatus (CustomerStatusBean unitBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            CustomerStatus unit = new CustomerStatus (unitBean.getName ());
            String unitId = unitBean.getId ();
            if (null != unitId && !"".equals (unitId))
            {
                unit.setId (Long.parseLong (unitId));
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                customerStatusDao.save (unit);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_CUSTOMER_STATUS))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                       ComponentConstants.MSG_CUSTOMER_STATUS))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/delCustomerStatus", method = RequestMethod.POST)
    public @ResponseBody
    String deleteCustomerStatus (@RequestParam String ids)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            List <CustomerStatus> customerStatuses = new ArrayList <CustomerStatus> ();
            CustomerStatus customerStatus;
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String typeId : idArr)
                {
                    customerStatus = new CustomerStatus ();
                    customerStatus.setId (Long.parseLong (typeId));
                    customerStatuses.add (customerStatus);
                }
            }
            else
            {
                customerStatus = new CustomerStatus ();
                customerStatus.setId (Long.parseLong (ids));
                customerStatuses.add (customerStatus);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                customerStatusDao.delete (customerStatuses);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_CUSTOMER_STATUS))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                       ComponentConstants.MSG_CUSTOMER_STATUS))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }
}
